﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;
using System.Drawing.Design;
using System.Xml;
using System.IO;

namespace PPCodes.ToolBoxPad
{
    public partial class AddComponents : Form
    {
        private ConfigureToolBox ctb;


        #region 初始化
        
        public AddComponents()
        {
            InitializeComponent();
        }

        public AddComponents(ConfigureToolBox _ctb)
        {
            InitializeComponent();
            ctb = _ctb;
        }

        private void AddComponents_Load(object sender, EventArgs e)
        {
            LoadAllAssembly();
        }  
        #endregion 

        /// <summary>
        /// 获取最佳程序集
        /// </summary>
        private void LoadAllAssembly()
        {
            try
            {
                foreach (DomAssemblyName asm in GacInterop.GetAssemblyList())
                {
                    gvGAC.Rows.Add();
                    gvGAC.Rows[gvGAC.Rows.Count - 1].Cells["colName"].Value = asm.ShortName;
                    gvGAC.Rows[gvGAC.Rows.Count - 1].Cells["colVersion"].Value = asm.Version.ToString();
                    gvGAC.Rows[gvGAC.Rows.Count - 1].Cells["colFullName"].Value = asm.FullName;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (gvComponents.Visible == false || gvComponents.Rows.Count==0)
            {
                MessageBox.Show("No components added");
                return;
            }

            List<DataGridViewRow> list = new List<DataGridViewRow>();

            foreach (DataGridViewRow dr in gvComponents.Rows)
            {
                if (Convert.ToBoolean(dr.Cells["colCheckBox"].Value)==true)
                {
                    list.Add(dr);
                }
            }
            ctb.AddNewComponentsToGridAndRefresh(list);
            this.Close();

        }

        /// <summary>
        /// 文件选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.AddExtension = true;
            ofd.Filter = "*.dll|*.dll|*.exe|*.exe|所有文件(*.*)|*.*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtFile.Text = ofd.FileName;
            }
        }

        /// <summary>
        /// 显示包含的工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShow_Click(object sender, EventArgs e)
        {
            {
                BeginFillComponentsGrid();
                try
                {
                    string assemblyFileNames = txtFile.Text.Trim();
                    Assembly lastAssembly = null;
                    foreach (string assemblyFileName in assemblyFileNames.Split(';'))
                    {
                        if (!File.Exists(assemblyFileName))
                        {
                            EndFillComponentsGrid(null);
                            ClearComponentsGrid(assemblyFileName + " was not found.");
                            //MessageBox.Show("$ponents.EnterValidFilename}");
                            return;
                        }

                        Assembly asm = Assembly.LoadFrom(assemblyFileName);
                        lastAssembly = asm;
                        AddComponentsToGrid(asm, Path.GetDirectoryName(assemblyFileName));
                    }
                    EndFillComponentsGrid(lastAssembly);
                }
                catch
                {
                    EndFillComponentsGrid(null);
                    //MessageService.ShowWarning("${res:ICSharpCode.SharpDevelop.FormDesigner.Gui.AddSidebarComponents.FileIsNotAssembly}");
                    ClearComponentsGrid(null);
                }
            }


        }




        #region 控件读取主方法 
        
        void AddComponentsToGrid(Assembly assembly, string loadPath)
        {
            if (assembly != null)
            {
                Dictionary<string, int> images = new Dictionary<string, int>();
                ImageList il = new ImageList();
                //il.Images.Add(new Bitmap(1, 1));
                // try to load res icon
                string[] imgNames = assembly.GetManifestResourceNames();
                foreach (string im in imgNames)
                {
                    try
                    {
                        Bitmap b = new Bitmap(Image.FromStream(assembly.GetManifestResourceStream(im)));
                        b.MakeTransparent();
                        images[im] = il.Images.Count;
                        il.Images.Add(b);
                        //images[im]=b;
                    }
                    catch { }
                }
                try
                {
                    foreach (Type t in assembly.GetExportedTypes())
                    {
                        if (!t.IsAbstract)
                        {
                            if (t.IsDefined(typeof(ToolboxItemFilterAttribute), true) || t.IsDefined(typeof(ToolboxItemAttribute), true) || typeof(System.ComponentModel.IComponent).IsAssignableFrom(t))
                            {
                                object[] attributes = t.GetCustomAttributes(false);
                                object[] filterAttrs = t.GetCustomAttributes(typeof(DesignTimeVisibleAttribute), true);
                                foreach (DesignTimeVisibleAttribute visibleAttr in filterAttrs)
                                {
                                    if (!visibleAttr.Visible)
                                    {
                                        goto skip;
                                    }
                                }

                                if (!images.ContainsKey(t.FullName + ".bmp"))
                                {
                                    if (t.IsDefined(typeof(ToolboxBitmapAttribute), false))
                                    {
                                        foreach (object attr in attributes)
                                        {
                                            if (attr is ToolboxBitmapAttribute)
                                            {
                                                ToolboxBitmapAttribute toolboxBitmapAttribute = (ToolboxBitmapAttribute)attr;
                                                images[t.FullName + ".bmp"] = il.Images.Count;
                                                Bitmap b = new Bitmap(toolboxBitmapAttribute.GetImage(t));
                                                b.MakeTransparent();
                                                il.Images.Add(b);
                                                break;
                                            }
                                        }
                                    }
                                }
                                gvComponents.Rows.Add();
                                gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colCheckBox"].Value = true;

                                gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colName2"].Value = t.Name;
                                gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colNameSpace"].Value = t.Namespace;
                                gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colAssembly"].Value = assembly.ToString();
                                gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colLocation"].Value = assembly.Location;

                                if (images.ContainsKey(t.FullName + ".bmp"))
                                {
                                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colImage"].Value = il.Images[(int)images[t.FullName + ".bmp"]];
                                }
                                else
                                {
                                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colImage"].Value = new Bitmap(1, 1);
                                }

                                ToolComponent toolComponent = new ToolComponent(t.FullName, new ComponentAssembly(assembly.FullName, loadPath), true);
                                gvComponents.Rows[gvComponents.Rows.Count - 1].Tag = toolComponent;

                                ToolboxItem item = new ToolboxItem(t);

                            skip: ;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ClearComponentsGrid(ex.Message);
                }
            }
        }

        void BeginFillComponentsGrid()
        {
            tlpGV.Visible = true;
            txtInfo.Visible = false;
            txtInfo.Text = "";
            gvComponents.Rows.Clear();
        }

        void EndFillComponentsGrid(Assembly lastAssembly)
        {
            if (gvComponents.Rows.Count == 0)
            {
                if (lastAssembly != null)
                {
                    ClearComponentsGrid(String.Format("{0} don not contain any components", lastAssembly.FullName));
                }
                else
                {
                    ClearComponentsGrid("Can not load the selected assembly");
                }
            }
        }

        void ClearComponentsGrid(string message)
        {
            tlpGV.Visible = false;
            gvComponents.Rows.Clear();
            txtInfo.Visible = true;
            txtInfo.Text = "";
            if (message != null)
            {
                txtInfo.Text = message;
            }
            else
            {
                txtInfo.Text = "";
            }
        } 
        #endregion


        #region 控件列表
        
        /// <summary>
        /// 左边行单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvGAC_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (true)
            //{
                try
                {
                    string assemblyName = gvGAC.Rows[e.RowIndex].Cells["colFullName"].Value.ToString();
                    Assembly asm = Assembly.Load(assemblyName);
                    BeginFillComponentsGrid();
                    AddComponentsToGrid(asm, null);
                    EndFillComponentsGrid(asm);
                }
                catch (Exception ex)
                {
                    EndFillComponentsGrid(null);
                    ClearComponentsGrid(ex.Message);
                }
            //}
            //else
            //{
            //    ClearComponentsGrid(null);
            //}
        }


        /// <summary>
        /// 右边单元格单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvComponents_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (Convert.ToBoolean(gvComponents.Rows[e.RowIndex].Cells[0].Value))
            {
                gvComponents.Rows[e.RowIndex].Cells[0].Value = false;
            }
            else
            {
                gvComponents.Rows[e.RowIndex].Cells[0].Value = true;
            }
        }


        /// <summary>
        /// 选择全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvComponents.Rows.Count; i++)
            {
                gvComponents.Rows[i].Cells[0].Value = true;
            }
        }


        /// <summary>
        /// 全部不选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectNo_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvComponents.Rows.Count; i++)
            {
                gvComponents.Rows[i].Cells[0].Value = false;
            }
        } 
        #endregion






    }
}
